<template>
  <div class="home-container">
    <van-nav-bar title="头 条" fixed/>
    <van-pull-refresh v-model="refreshing" :disabled="finished" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <ArticleInfo v-for="item in articleList" :key="item.id" :title="item.title" :author="item.aut_name"
                     :comm-count="item.comm_count" :time="item.pubdate" :cover="item.cover"></ArticleInfo>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleInfo from '@/components/article/ArticleInfo'
import { getArticleListAPI } from '@/api/articleApi'
import _ from 'lodash'

let fn = null
export default {
  name: 'MyHome',
  data () {
    return {
      page: 1,
      limit: 10,
      articleList: [],
      loading: true, // 是否正在加载下一页数据，如果loading为true，则不会反复触发load事件
      finished: false, // 所有的数据是否都加载完毕，如果loading为true，则不会反复触发load事件
      refreshing: false // 是否正在下拉刷新
    }
  },
  components: {
    ArticleInfo
  },
  methods: {
    // 获取文章列表数据
    async initArticleList (isRefresh) {
      const { data: res } = await getArticleListAPI(this.page, this.limit)
      if (isRefresh) {
        // 下拉刷新
        this.articleList = [...res, ...this.articleList] // 新旧数据进行拼接
        this.refreshing = false
      } else {
        // 上拉加载
        this.articleList = [...this.articleList, ...res] // 新旧数据进行拼接
        this.loading = false
      }
      if (res.length === 0) { // 判断是否还有下一页
        this.finished = true
      }
    },
    onLoad () { // 上拉加载
      // 页码值+1
      this.page++
      // 请求文章数据
      this.initArticleList()
    },
    onRefresh () { // 下拉刷新
      this.page++
      this.initArticleList(true)
    },
    recordTopHandler () {
      // 防抖
      return _.debounce(() => {
        this.$route.meta.top = window.scrollY
      }, 50, { trailing: true })
    }
  },
  created () {
    this.initArticleList()
  },
  activated () {
    fn = this.recordTopHandler()
    window.addEventListener('scroll', fn)
  },
  deactivated () {
    window.removeEventListener('scroll', fn)
  }
}
</script>

<style lang="less" scoped>
.home-container {
  padding: 46px 0 50px 0;

  /*.van-nav-bar {
    background-color: #007bff;
  }

  /deep/ .van-nav-bar__title {
    color: #fff;
  }*/
}
</style>
